package com.hengpeng.itfin.job.mail;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hengpeng.common.cis.ComponentContextLoader;
import com.hengpeng.common.scheduling.AbstractJob;
import com.hengpeng.common.scheduling.ScheduleConfig;
import com.hengpeng.itfin.job.mail.support.MailSender;
import com.hengpeng.itfin.service.EmailService;
import com.hengpeng.itfinbase.persist.EmailLog;

/**
 * <pre>
 * 发送邮件任务
 * 每10秒钟扫描一遍表,取出100条记录
 * </pre>
 * @author shanguogang
 * @version 1.0, 2015-07-31
 */
public class SendMail extends AbstractJob
{

	private static final Log log = LogFactory.getLog(SendMail.class);

	private static int fetchCount=100;

	private static boolean firstExec = true;

	@Override
	public void exec(boolean isTimeout, ScheduleConfig config)
	{
		EmailService service = ComponentContextLoader.getBean(EmailService.class);
		// log.info("发送邮件作业开始...");
		if (MailSender.isStop())
		{
			log.info("sorry!邮件发送线程未启动,将在下次任务时重试!");

			Thread t = new Thread()
			{
				public void run()
				{
					MailSender.getInstance().start();
				}
			};
			t.setDaemon(true);
			t.start();
			return;
		}
		if (firstExec)
		{
			int count = service.resetAllEmailForSending();
			log.info("发送邮件作业首次启动，共有[" + count + "]条发送中状态的邮件记录被重置");
			firstExec = false;
		}
		List<EmailLog> list = service.findEmailForNotSend(fetchCount);
		log.info("共获取[" + list.size() + "]条待发送邮件");
		for (EmailLog email : list)
		{
			MailSender.getInstance().send(email);
		}
	}
}
